import app from "@/config/app"

export default {
	// 定位
	location(succ: any, fail = () => {}){
		const that = this
		uni.getLocation({
			type: 'gcj02',
			success (res: {longitude: string, latitude: string}) {
				const point = {
					lng: res.longitude,
					lat: res.latitude
				}
				that.regeo(point).then((result: object)=>{
					succ({ ...result, ...point })				
				})
			},
			fail (res: object) {
				fail()
			}
		})		
	},
	choose(succ: any){
		const that = this
		uni.chooseLocation({
			success(res){
				const point = {
					lng: res.longitude,
					lat: res.latitude
				}
				that.regeo(point).then((result: any)=>{
					succ({ ...result, point: point })			
				})
			}
		})		
	},
	get(path: string = '', params = {}){
		params.key = app.gaode
		return uni.request({
			url: 'https://restapi.amap.com/v5/' + path,
			data: params
		}).then(({data: any}) => {
			if(data.status==1){
				return data
			}
			return false
		})		
	},
	// 地理编码
	geo(res: {city_id: number, address: string}){
		return uni.request({
			url: 'https://restapi.amap.com/v3/geocode/geo',
			data: {city: res.city_id, address: res.address, key: app.gaode}
		}).then(({data: {geocodes: [{location,street,district}]}}) => {
			return {
				location: location,
				street: street,
				district: district
			}
		})
	},
	// 逆地理编码
	regeo(res: {lng: string, lat: string}){
		return uni.request({
			url: 'https://restapi.amap.com/v3/geocode/regeo',
			data: {output:'json', location:res.lng + ',' + res.lat, key: app.gaode, radius: 500, extensions: 'all'}
		}).then(({data: {regeocode:{formatted_address='',addressComponent={},aois=''}}}) => {
			return {
				city_id: Math.floor(addressComponent.adcode / 100) * 100,
				name: aois.length>0?aois[0].name:formatted_address,
				street: addressComponent.streetNumber.street,
				city_name: typeof(addressComponent.city) == 'object' ? '' : addressComponent.city.replace('市', ''),
				dist_id: addressComponent.adcode * 1,
				dist_name: typeof(addressComponent.district) == 'object' ? '' : addressComponent.district.replace('区', ''),
				address: addressComponent.streetNumber.street + addressComponent.streetNumber.number
			}
		})
	},
	search(keywords: string, city: number = 0, page: number = 1){
		return this.get('place/text', {
			keywords: keywords,
			region: city,
			city_limit: city>0,
			page: page
		}).then(({suggestion, pois}) => {
			return pois
		})
	},
	around(point, keywords: string = '', city: number = 0, page: number = 1){
		return this.get('place/around', {
			keywords: keywords,
			location: point.lat + ',' + point.lng,
			region: city,
			city_limit: city>0,
			radius: 50000,
			page: page
		}).then(({suggestion, pois}) => {
			return pois
		})		
	}
}